<?php
// +----------------------------------------------------------------------
// | Bwsaas
// +----------------------------------------------------------------------
// | Copyright (c) 2015~2020 http://www.buwangyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Gitee ( https://gitee.com/buwangyun/bwsaas )
// +----------------------------------------------------------------------
// | Author: buwangyun <hnlg666@163.com>
// +----------------------------------------------------------------------
// | Date: 2020-9-28 10:55:00
// +----------------------------------------------------------------------

namespace app\common\middleware;

use think\Request;

/**
 * 跨域处理
 * Class Auth
 * @package app\admin\middleware
 */
class Cross
{
    /**
     * @param Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, \Closure $next)
    {
        $origin = $request->header('Origin', '*');
        // 定义允许的请求头（根据你的需求调整）
        $allowHeaders = 'request-app, scopes, request-time, session_id, token, Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-Requested-With, invite-codes, invite_codes';
        // 如果是 OPTIONS 预检请求
        if ($request->isOptions()) {
            return response()
                ->header([
                    'Access-Control-Allow-Origin' => $origin,
                    'Access-Control-Allow-Headers' => $allowHeaders,
                    'Access-Control-Allow-Methods' => 'GET, POST, PATCH, PUT, DELETE, OPTIONS',
                    'Access-Control-Allow-Credentials' => 'true',
                    'Access-Control-Max-Age' => '1728000',
                    'Content-Type' => 'text/plain; charset=UTF-8'
                ])
                ->code(204);
        }
        // 正常请求的处理
        $response = $next($request);

        // 添加 CORS 头
        return $response->header([
            'Access-Control-Allow-Origin' => $origin,
            'Access-Control-Allow-Credentials' => 'true'
        ]);
    }
}